﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using eProject.Model;

namespace eProject.Logic
{
    public class Tasks //TODO Serializable?
    {

        public Tasks()
        {
        }        

        private readonly Dictionary<Task, double> _tasks = new Dictionary<Task, double>();

        public long Count { get { return _tasks.Count; } }

        public delegate void TaskEventHandler(Task task);

        public event TaskEventHandler TaskAdded;

        private void InvokeTaskAdded(Task task)
        {
            var handler = TaskAdded;
            if (handler != null) handler(task);
        }

        public event TaskEventHandler TaskRemoved;

        private void InvokeTaskRemoved(Task task)
        {
            var removed = TaskRemoved;
            if (removed != null) removed(task);
        }

        public event TaskEventHandler TaskChanged;

        private void InvokeTaskChanged(Task task)
        {
            var changed = TaskChanged;
            if (changed != null) changed(task);
        }  

        public void AddTask(Task task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            _tasks.Add(task,0);
            task.TaskChanged += TaskChangedEventHandler;
            InvokeTaskAdded(task);
        }

        public void RemoveTask(Task task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            _tasks.Remove(task);
            task.TaskChanged -= TaskChangedEventHandler;
            InvokeTaskRemoved(task);
        }   
     
        public IEnumerable<Task> GetTasks()
        {
            return _tasks.Keys;
        }        

       
        private void TaskChangedEventHandler(Task task)
        {
            InvokeTaskChanged(task);
        }
        
    }
}
